package com.punai.framework.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.punai.common.utils.SecurityUtils;
import com.punai.framework.config.mybatilsplus.MySqlInjector;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.HashSet;


@EnableTransactionManagement(proxyTargetClass = true)
@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor()
    {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

/*        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                try {
                    Long companyId = SecurityUtils.getCompanyId();
                    return new LongValue(companyId);
                }catch (Exception e) {
                    return new LongValue(-1L);
                }
            }
            @Override
            public String getTenantIdColumn() {
                return "company_id";
            }

            // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
            @Override
            public boolean ignoreTable(String tableName) {
                try{

                    Long userId = SecurityUtils.getUserId();
                    boolean admin = SecurityUtils.isAdmin(userId);
                    if (admin) {
                        return true;
                    }

                    Long companyId = SecurityUtils.getCompanyId();
                    if (companyId == null) {
                        return true;
                    }
                }catch (Exception e) {
                    return true;
                }
                HashSet<String> ignoreTables = new HashSet<>();
                ignoreTables.add("sys_dict_data");
                ignoreTables.add("sys_dict_type");
                ignoreTables.add("sys_job");
                ignoreTables.add("sys_job_log");
                ignoreTables.add("sys_logininfor");
                ignoreTables.add("sys_menu");
                ignoreTables.add("sys_notice");
                ignoreTables.add("sys_oper_log");
                ignoreTables.add("sys_role_menu");
                ignoreTables.add("sys_role_dept");
                ignoreTables.add("sys_user_post");
                ignoreTables.add("sys_user_role");
                ignoreTables.add("sys_config");
                ignoreTables.add("gen_table");
                ignoreTables.add("gen_table_column");
                ignoreTables.add("qrtz_blob_triggers");
                ignoreTables.add("qrtz_calendars");
                ignoreTables.add("qrtz_cron_triggers");
                ignoreTables.add("qrtz_fired_triggers");
                ignoreTables.add("qrtz_job_details");
                ignoreTables.add("qrtz_locks");
                ignoreTables.add("qrtz_paused_trigger_grps");
                ignoreTables.add("qrtz_scheduler_state");
                ignoreTables.add("qrtz_simple_triggers");
                ignoreTables.add("qrtz_simprop_triggers");
                ignoreTables.add("qrtz_triggers");
                return ignoreTables.contains(tableName.toLowerCase());
            }
        }));*/
        // 分页插件
        interceptor.addInnerInterceptor(paginationInnerInterceptor());
        // 乐观锁插件
        interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
        // 阻断插件
        interceptor.addInnerInterceptor(blockAttackInnerInterceptor());
        return interceptor;
    }

    /**
     * 分页插件，自动识别数据库类型 https://baomidou.com/guide/interceptor-pagination.html
     */
    public PaginationInnerInterceptor paginationInnerInterceptor()
    {
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 设置数据库类型为mysql
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInnerInterceptor.setMaxLimit(-1L);
        return paginationInnerInterceptor;
    }

    /**
     * 乐观锁插件 https://baomidou.com/pages/0d93c0/#optimisticlockerinnerinterceptor
     *
     * 2.在实体类的字段上加上@Version注解
     * @Version
     * private Integer version;
     * 说明:
     *
     * 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
     * 整数类型下 newVersion = oldVersion + 1
     * newVersion 会回写到 entity 中
     * 仅支持 updateById(id) 与 update(entity, wrapper) 方法
     * 在 update(entity, wrapper) 方法下, wrapper 不能复用!!!
     */
    public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor()
    {
        return new OptimisticLockerInnerInterceptor();
    }

    /**
     * 如果是对全表的删除或更新操作，就会终止该操作 https://baomidou.com/guide/interceptor-block-attack.html
     */
    public BlockAttackInnerInterceptor blockAttackInnerInterceptor()
    {
        return new BlockAttackInnerInterceptor();
    }

    /**
     * 批量插入定义 注入器
     */
    @Bean
    public MySqlInjector sqlInjector() {
        return new MySqlInjector();
    }
}
